package com.finance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finance.entity.GoodsOperationDetail;
import com.finance.mapper.GoodsOperationDetailMapper;
import com.finance.service.GoodsOperationDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * C15
 * 商品操作明细数据Service实现类
 */
@Slf4j
@Service
public class GoodsOperationDetailServiceImpl extends ServiceImpl<GoodsOperationDetailMapper, GoodsOperationDetail> implements GoodsOperationDetailService {

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int processOrders(List<Map<String, String>> records, String searchDate, boolean forceUpdate, String cinemaId) {
        if (records == null || records.isEmpty()) {
            return 0;
        }

        // 如果强制更新，先删除指定日期和影院ID的数据
        if (forceUpdate) {
            LambdaQueryWrapper<GoodsOperationDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(GoodsOperationDetail::getSearchDate, searchDate)
                  .eq(GoodsOperationDetail::getCinemaId, cinemaId);
            this.remove(wrapper);
        }

        List<GoodsOperationDetail> operations = new ArrayList<>();
        for (Map<String, String> record : records) {
            try {
                GoodsOperationDetail operation = new GoodsOperationDetail();
                operation.setCinemaId(cinemaId);
                //影院八位编码,影院名称,调入/调出影院专资编码,调入/调出影院名称,操作类型,说明,库存地点类型,库存地点,货品名称,货品编码
                if (StringUtils.hasText(record.get("影院八位编码"))) {
                    operation.setCinemaCode(record.get("影院八位编码"));
                }
                if (StringUtils.hasText(record.get("影院名称"))) {
                    operation.setCinemaName(record.get("影院名称"));
                }
                if (StringUtils.hasText(record.get("调入/调出影院专资编码"))) {
                    operation.setTransferCinemaCode(record.get("调入/调出影院专资编码"));
                }
                if (StringUtils.hasText(record.get("调入/调出影院名称"))) {
                    operation.setTransferCinemaName(record.get("调入/调出影院名称"));
                }
                if (StringUtils.hasText(record.get("操作类型"))) {
                    operation.setOperationType(record.get("操作类型"));
                }
                if (StringUtils.hasText(record.get("说明"))) {
                    operation.setDescription(record.get("说明"));
                }
                if (StringUtils.hasText(record.get("库存地点类型"))) {
                    operation.setInventoryLocationType(record.get("库存地点类型"));
                }
                if (StringUtils.hasText(record.get("库存地点"))) {
                    operation.setInventoryLocation(record.get("库存地点"));
                }
                if (StringUtils.hasText(record.get("货品名称"))) {
                    operation.setGoodsName(record.get("货品名称"));
                }
                if (StringUtils.hasText(record.get("货品编码"))) {
                    operation.setGoodsCode(record.get("货品编码"));
                }
                // 税率,盘前库存
                String taxRateStr = record.get("税率");
                if (StringUtils.hasText(taxRateStr)) {
                    try {
                        operation.setTaxRate(new BigDecimal(taxRateStr));
                    } catch (Exception e) {
                        log.warn("Invalid tax rate format: {}", taxRateStr);
                    }
                }
                String preInventoryStr = record.get("盘前库存");
                if (StringUtils.hasText(preInventoryStr)) {
                    try {
                        operation.setPreInventory(new BigDecimal(preInventoryStr));
                    } catch (Exception e) {
                        log.warn("Invalid pre inventory format: {}", preInventoryStr);
                    }
                }
                // 供应商,单位,是否赠品,操作数量,含税单价
                if (StringUtils.hasText(record.get("供应商"))) {
                    operation.setSupplier(record.get("供应商"));
                }
                if (StringUtils.hasText(record.get("单位"))) {
                    operation.setUnit(record.get("单位"));
                }
                if (StringUtils.hasText(record.get("是否赠品"))) {
                    operation.setIsGift(record.get("是否赠品"));
                }
                
                // 处理操作数量
                String operationQuantityStr = record.get("操作数量");
                if (StringUtils.hasText(operationQuantityStr)) {
                    try {
                        operation.setOperationQuantity(new BigDecimal(operationQuantityStr));
                    } catch (Exception e) {
                        log.warn("Invalid operation quantity format: {}", operationQuantityStr);
                    }
                }
                
                // 处理含税单价
                String taxIncludedPriceStr = record.get("含税单价");
                if (StringUtils.hasText(taxIncludedPriceStr)) {
                    try {
                        operation.setTaxIncludedPrice(new BigDecimal(taxIncludedPriceStr));
                    } catch (Exception e) {
                        log.warn("Invalid tax included price format: {}", taxIncludedPriceStr);
                    }
                }
                // 不含税单价,含税金额,订单号,操作员,操作员工号
                String taxExcludedPriceStr = record.get("不含税单价");
                if (StringUtils.hasText(taxExcludedPriceStr)) {
                    try {
                        operation.setTaxExcludedPrice(new BigDecimal(taxExcludedPriceStr));
                    } catch (Exception e) {
                        log.warn("Invalid tax excluded price format: {}", taxExcludedPriceStr);
                    }
                }
                String taxIncludedAmountStr = record.get("含税金额");
                if (StringUtils.hasText(taxIncludedAmountStr)) {
                    try {
                        operation.setTaxIncludedAmount(new BigDecimal(taxIncludedAmountStr));
                    } catch (Exception e) {
                        log.warn("Invalid tax included amount format: {}", taxIncludedAmountStr);
                    }
                }
                if (StringUtils.hasText(record.get("订单号"))) {
                    operation.setOrderNo(record.get("订单号"));
                }
                if (StringUtils.hasText(record.get("操作员"))) {
                    operation.setOperator(record.get("操作员"));
                }
                if (StringUtils.hasText(record.get("操作员工号"))) {
                    operation.setOperatorEmployeeNo(record.get("操作员工号"));
                }
                // 操作时间,调拨出库单号,入库单号
                String operationTimeStr = record.get("操作时间");
                if (StringUtils.hasText(operationTimeStr)) {
                    try {
                        operation.setOperationTime(LocalDateTime.parse(operationTimeStr, DATE_TIME_FORMATTER));
                    } catch (Exception e) {
                        log.warn("Invalid operation time format: {}", operationTimeStr);
                    }
                }
                if (StringUtils.hasText(record.get("调拨出库单号"))) {
                    operation.setTransferOutOrderNo(record.get("调拨出库单号"));
                }
                if (StringUtils.hasText(record.get("入库单号"))) {
                    operation.setStorageInOrderNo(record.get("入库单号"));
                }
                operation.setSearchDate(searchDate);
                // 处理新增字段
                if (StringUtils.hasText(record.get("一级分类"))) {
                    operation.setFirstCategory(record.get("一级分类"));
                }
                if (StringUtils.hasText(record.get("供应商外部编码"))) {
                    operation.setSupplierExternalCode(record.get("供应商外部编码"));
                }
                if (StringUtils.hasText(record.get("销售大类"))) {
                    operation.setSalesCategory(record.get("销售大类"));
                }
                operations.add(operation);
            } catch (Exception e) {
                log.error("Error processing C15 record: {}", record, e);
                throw new RuntimeException("Failed to process C15 record", e);
            }
        }

        try {
            saveBatch(operations);
            return operations.size();
        } catch (Exception e) {
            log.error("Error saving C15 data batch", e);
            throw new RuntimeException("Failed to save C15 data batch", e);
        }
    }
} 